package me.leiusual.sharing.api

import android.content.Context
import dagger.Module
import dagger.Provides
import me.leiusual.sharing.api.cookie.CookieJarImpl
import me.leiusual.sharing.api.interceptor.InterceptorImpl
import me.leiusual.sharing.util.extension.gson
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * Create by leiusual on 2018/7/18
 */
@Module
class ApiModule {

  companion object {
    private const val HTTP = "http"
  }

  @Singleton
  @Provides
  fun okHttpClient(context: Context, interceptorImpl: InterceptorImpl): OkHttpClient {

    val dir = File(context.cacheDir, HTTP)
    val cache = Cache(dir, 10L shl 20)

    val httpLoggingInterceptor = HttpLoggingInterceptor { Timber.d(it) }
    httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

    return OkHttpClient.Builder()
        .callTimeout(30, TimeUnit.SECONDS)
        .cookieJar(CookieJarImpl())
        .cache(cache)
        .addInterceptor(interceptorImpl)
        .addNetworkInterceptor(httpLoggingInterceptor)
        .build()
  }

  @Singleton
  @Provides
  fun retrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .baseUrl("http://localhost")
        .client(okHttpClient)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()
  }

  @Singleton
  @Provides
  fun oauth2Api(retrofit: Retrofit): ApiOauth2 {
    return retrofit.newBuilder()
        .baseUrl(ApiOauth2.BASE_URL)
        .build()
        .create(ApiOauth2::class.java)
  }

  @Singleton
  @Provides
  fun sharingApi(retrofit: Retrofit): ApiSharing {
    return retrofit.newBuilder()
        .baseUrl(ApiSharing.BASE_URL)
        .build()
        .create(ApiSharing::class.java)
  }
}